// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.SellOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.SellOrderMapper;
import com.fowo.api.mapper.SellOrderTransactionDetailsMapper;
import com.fowo.api.model.sell.order.SellOrderExcelPo;
import com.fowo.api.model.sell.order.SellOrderItemVo;
import com.fowo.api.model.sell.order.SellOrderSearchParamPo;
import com.fowo.api.model.sell.order.SellOrderVo;
import com.fowo.api.model.sell.order.detail.SellOrderDetailSearchParamPo;
import com.fowo.api.model.sell.order.exchange.goods.SellOrderExchangeGoodsSearchParamPo;
import com.fowo.api.model.sell.order.transaction.details.SellOrderTransactionDetailsSearchParamPo;
import com.fowo.api.model.sell.orderreturn.SellOrderreturnSearchParamPo;
import com.fowo.api.service.SellOrderDetailService;
import com.fowo.api.service.SellOrderExchangeGoodsService;
import com.fowo.api.service.SellOrderService;
import com.fowo.api.service.SellOrderTransactionDetailsService;
import com.fowo.api.service.SellOrderreturnService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单列表 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，吕家傲
 */
@Service
@Slf4j
@DataObjectType(SellOrder.class)
@DS("ds24")
public class SellOrderServiceImpl
  extends ServiceImpl<SellOrderMapper, SellOrder>
  implements SellOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("sidShopName", "si.`shop_name`");
      put("countryName", "sr.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected SellOrderService self;

  @Resource
  protected SellOrderDetailService sellOrderDetailService;

  @Resource
  protected SellOrderreturnService sellOrderreturnService;

  @Resource
  protected SellOrderExchangeGoodsService sellOrderExchangeGoodsService;

  @Resource
  protected SellOrderTransactionDetailsService sellOrderTransactionDetailsService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建订单列表
   * @param model 订单列表
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SellOrder entity = new SellOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getIsAssessed() == null) {
      entity.setIsAssessed(false);
    }

    if (model.getIsMcfOrder() == null) {
      entity.setIsMcfOrder(false);
    }

    if (model.getIsReturnOrder() == null) {
      entity.setIsReturnOrder(false);
    }

    if (model.getIsReplacedOrder() == null) {
      entity.setIsReplacedOrder(false);
    }

    if (model.getIsReplacementOrder() == null) {
      entity.setIsReplacementOrder(false);
    }

    if (model.getIsBusinessOrder() == null) {
      entity.setIsBusinessOrder(false);
    }

    if (model.getIsPrime() == null) {
      entity.setIsPrime(false);
    }

    if (model.getIsPremiumOrder() == null) {
      entity.setIsPremiumOrder(false);
    }

    if (model.getIsPromotion() == null) {
      entity.setIsPromotion(false);
    }

    if (model.getTaxesIncluded() == null) {
      entity.setTaxesIncluded(false);
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("订单列表保存失败");
  }

  /**
   * 更新所有子表
   * @param model 订单列表
   */
  protected void updateAllChilds(SellOrderVo model) throws Exception {
    if (model.getDetails() != null) {
      sellOrderDetailService.saveAllBySellOrderDetails(
        model,
        model.getDetails()
      );
    }

    if (model.getReturnInfo() != null) {
      sellOrderreturnService.saveAllBySellOrderReturnInfo(
        model,
        model.getReturnInfo()
      );
    }

    if (model.getChangeInfo() != null) {
      sellOrderExchangeGoodsService.saveAllBySellOrderChangeInfo(
        model,
        model.getChangeInfo()
      );
    }

    if (model.getTransactionInfo() != null) {
      sellOrderTransactionDetailsService.saveAllByParentSellOrder(
        model.getId(),
        model.getTransactionInfo()
      );
    }
  }

  /**
   * 更新订单列表
   * @param model 订单列表
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SellOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单列表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新订单列表（带空值）
   * @param model 订单列表
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SellOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单列表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(SellOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(SellOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(SellOrder::getSid, model.getSid())
      .set(SellOrder::getCountry, model.getCountry())
      .set(SellOrder::getAmazonOrderId, model.getAmazonOrderId())
      .set(SellOrder::getFulfillmentChannel, model.getFulfillmentChannel())
      .set(SellOrder::getBuyerName, model.getBuyerName())
      .set(SellOrder::getBuyerEmail, model.getBuyerEmail())
      .set(SellOrder::getPurchaseDateLocal, model.getPurchaseDateLocal())
      .set(SellOrder::getOrderStatus, model.getOrderStatus())
      .set(SellOrder::getPostedDate, model.getPostedDate())
      .set(SellOrder::getShipmentDate, model.getShipmentDate())
      .set(SellOrder::getShipServiceLevel, model.getShipServiceLevel())
      .set(SellOrder::getCarrier, model.getCarrier())
      .set(SellOrder::getTrackingNumber, model.getTrackingNumber())
      .set(SellOrder::getEarliestDeliveryDate, model.getEarliestDeliveryDate())
      .set(SellOrder::getName, model.getName())
      .set(SellOrder::getPostalCode, model.getPostalCode())
      .set(SellOrder::getPhone, model.getPhone())
      .set(SellOrder::getAddress, model.getAddress())
      .set(SellOrder::getSalesChannel, model.getSalesChannel())
      .set(SellOrder::getSellerOrderNumber, model.getSellerOrderNumber())
      .eq(SellOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(SellOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 交易明细(transactionInfo) 对应的对象
    SellOrderTransactionDetailsSearchParamPo transactionInfoSearchParam =
      new SellOrderTransactionDetailsSearchParamPo();
    transactionInfoSearchParam.setDisableDataPremissions(true);
    transactionInfoSearchParam.setParentSellOrderInList(ids);
    SellOrderTransactionDetailsMapper localSellOrderTransactionDetailsMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(SellOrderTransactionDetailsMapper.class);
    transactionInfoSearchParam.applySqlSegments();
    List<Long> transactionInfoIdList =
      localSellOrderTransactionDetailsMapper.searchIds(
        transactionInfoSearchParam
      );
    if (!transactionInfoIdList.isEmpty()) {
      SellOrderTransactionDetailsService localSellOrderTransactionDetailsService =
        ContextHolder
          .getApplicationContext()
          .getBean(SellOrderTransactionDetailsService.class);
      localSellOrderTransactionDetailsService.batchDelete(
        transactionInfoIdList
      );
    }
  }

  /**
   * 删除订单列表
   * @param id 订单列表的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除订单列表
   * @param ids 订单列表的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    SellOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "sid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SellOrderItemVo) r).getSidShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "country",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SellOrderItemVo) r).getCountryName())
          )
      );
      exportOptions.addFieldMappingOption(
        "fulfillmentChannel",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00116")
      );
      exportOptions.addFieldMappingOption(
        "requestReviewStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00114")
      );
      exportOptions.addFieldMappingOption(
        "orderStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00115")
      );
      exportOptions.addStringFields(
        "sidShopName",
        "countryName",
        "amazonOrderId",
        "fulfillmentChannel",
        "buyerName",
        "buyerEmail",
        "orderTotalAmount",
        "remark",
        "requestReviewStatus",
        "orderStatus",
        "sellerOrderNumber"
      );

      String fileName = String.format(
        "订单列表(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> fulfillmentChannelItems = sysDictService.getDictItems(
      "SCM00116"
    );
    List<SysDictAllItem> requestReviewStatusItems = sysDictService.getDictItems(
      "SCM00114"
    );
    List<SysDictAllItem> orderStatusItems = sysDictService.getDictItems(
      "SCM00115"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SellOrderExcelPo> items = new ArrayList<SellOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<SellOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SellOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SellOrderItemVo item : list) {
        SellOrderExcelPo excel = new SellOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getFulfillmentChannel() != null) {
          fulfillmentChannelItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getFulfillmentChannel()))
            .findFirst()
            .ifPresent(i -> excel.setFulfillmentChannel(i.getItemText()));
        }
        if (item.getRequestReviewStatus() != null) {
          requestReviewStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getRequestReviewStatus()))
            .findFirst()
            .ifPresent(i -> excel.setRequestReviewStatus(i.getItemText()));
        }
        if (item.getOrderStatus() != null) {
          orderStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getOrderStatus()))
            .findFirst()
            .ifPresent(i -> excel.setOrderStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "订单列表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SellOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过订单号查询订单列表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByAmazonOrderId(String amazonOrderId) {
    return this.baseMapper.getIdByAmazonOrderId(amazonOrderId);
  }

  /**
   * 通过订单号查询订单列表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByAmazonOrderId(List<String> list) {
    return this.baseMapper.getIdsByAmazonOrderId(list);
  }

  /**
   * 通过订单列表主键查询订单号
   */
  @Override
  public String getAmazonOrderIdById(Long id) {
    return this.baseMapper.getAmazonOrderIdById(id);
  }

  /**
   * 通过订单列表主键查询订单号列表
   */
  @Override
  public List<String> getAmazonOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getAmazonOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("amazonOrderId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 订单列表的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public SellOrderVo getVoById(Long id) throws Exception {
    SellOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    SellOrderDetailSearchParamPo detailsSearchParamPo =
      new SellOrderDetailSearchParamPo();
    detailsSearchParamPo.setAmazonOrderIdEq(vo.getAmazonOrderId());
    detailsSearchParamPo.applySqlSegments();
    detailsSearchParamPo.getExtendData().put("queryMode", "sub");
    detailsSearchParamPo.getExtendData().put("queryParent", "SellOrder");
    vo.setDetails(sellOrderDetailService.search(detailsSearchParamPo));

    SellOrderreturnSearchParamPo returnInfoSearchParamPo =
      new SellOrderreturnSearchParamPo();
    returnInfoSearchParamPo.setOrderIdEq(vo.getAmazonOrderId());
    returnInfoSearchParamPo.applySqlSegments();
    returnInfoSearchParamPo.getExtendData().put("queryMode", "sub");
    returnInfoSearchParamPo.getExtendData().put("queryParent", "SellOrder");
    vo.setReturnInfo(sellOrderreturnService.search(returnInfoSearchParamPo));

    SellOrderExchangeGoodsSearchParamPo changeInfoSearchParamPo =
      new SellOrderExchangeGoodsSearchParamPo();
    changeInfoSearchParamPo.setOriginalAmazonOrderIdEq(vo.getAmazonOrderId());
    changeInfoSearchParamPo.applySqlSegments();
    changeInfoSearchParamPo.getExtendData().put("queryMode", "sub");
    changeInfoSearchParamPo.getExtendData().put("queryParent", "SellOrder");
    vo.setChangeInfo(
      sellOrderExchangeGoodsService.search(changeInfoSearchParamPo)
    );

    SellOrderTransactionDetailsSearchParamPo transactionInfoSearchParamPo =
      new SellOrderTransactionDetailsSearchParamPo();
    transactionInfoSearchParamPo.setParentSellOrder(id);
    transactionInfoSearchParamPo.getExtendData().put("queryMode", "sub");
    transactionInfoSearchParamPo
      .getExtendData()
      .put("queryParent", "SellOrder");
    transactionInfoSearchParamPo.applySqlSegments();
    vo.setTransactionInfo(
      sellOrderTransactionDetailsService.search(transactionInfoSearchParamPo)
    );

    return vo;
  }

  /**
   * 主列表上要附加“商品信息”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfDetails(List<SellOrderItemVo> items, String sort) {
    SellOrderDetailSearchParamPo detailsSearchParamPo =
      new SellOrderDetailSearchParamPo();
    detailsSearchParamPo.setSort(sort);
    detailsSearchParamPo.setSelectFields(
      List.of(
        "amazonOrderId",
        "img",
        "title",
        "asin",
        "sellerSku",
        "quantityOrdered",
        "productId",
        "sku",
        "promotionIds"
      )
    );
    detailsSearchParamPo.setAmazonOrderIdInList(
      items
        .stream()
        .map(SellOrderItemVo::getAmazonOrderId)
        .collect(Collectors.toList())
    );
    sellOrderDetailService
      .search(detailsSearchParamPo)
      .forEach(details -> {
        SellOrderItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getAmazonOrderId(), details.getAmazonOrderId())
        );
        if (item == null) return;
        if (item.getDetailsImg() == null) {
          item.setDetailsImg(new ArrayList<>());
        }
        item.getDetailsImg().add(details.getImg());

        if (item.getDetailsTitle() == null) {
          item.setDetailsTitle(new ArrayList<>());
        }
        item.getDetailsTitle().add(details.getTitle());

        if (item.getDetailsAsin() == null) {
          item.setDetailsAsin(new ArrayList<>());
        }
        item.getDetailsAsin().add(details.getAsin());

        if (item.getDetailsSellerSku() == null) {
          item.setDetailsSellerSku(new ArrayList<>());
        }
        item.getDetailsSellerSku().add(details.getSellerSku());

        if (item.getDetailsQuantityOrdered() == null) {
          item.setDetailsQuantityOrdered(new ArrayList<>());
        }
        item.getDetailsQuantityOrdered().add(details.getQuantityOrdered());

        if (item.getDetailsProductId() == null) {
          item.setDetailsProductId(new ArrayList<>());
        }
        item.getDetailsProductId().add(details.getProductId());

        if (item.getDetailsProductIdName() == null) {
          item.setDetailsProductIdName(new ArrayList<>());
        }
        item.getDetailsProductIdName().add(details.getProductIdName());

        if (item.getDetailsSku() == null) {
          item.setDetailsSku(new ArrayList<>());
        }
        item.getDetailsSku().add(details.getSku());

        if (item.getDetailsPromotionIds() == null) {
          item.setDetailsPromotionIds(new ArrayList<>());
        }
        item.getDetailsPromotionIds().add(details.getPromotionIds());
      });
  }

  /**
   * 分页查询订单列表
   * @param search 查询条件
   * @return 订单列表分页查询结果
   */
  @Override
  public Page<SellOrderItemVo> pageSearch(SellOrderSearchParamPo search) {
    Page<SellOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 订单列表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SellOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SellOrderItemVo>> searchOptions(
    SellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询订单列表
   * @param search 查询条件
   * @return 订单列表列表查询结果
   */
  @Override
  public List<SellOrderItemVo> search(SellOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询订单列表最后更新时间
   * @param search 查询条件
   * @return 订单列表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SellOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 销售订单
   */
  @Override
  public List<SellOrderItemVo> sellOrder(SellOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.sellOrder(search);
  }

  /**
   * 销售订单分页
   */
  @Override
  public Page<SellOrderItemVo> sellOrderPage(SellOrderSearchParamPo search) {
    Page<SellOrderItemVo> sellOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return sellOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return sellOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    sellOrderPage =
      this.baseMapper.sellOrderPage(
          search.toPage(this.baseMapper.sellOrderCount(search)),
          search
        );
    if (
      search.getFillParts() == null || search.getFillParts().contains("details")
    ) {
      fillPartOfDetails(
        sellOrderPage.getRecords(),
        search.toChildSort("details")
      );
    }
    List<Long> recordIds = sellOrderPage
      .getRecords()
      .stream()
      .map(SellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return sellOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return sellOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    sellOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return sellOrderPage;
  }

  /**
   * 查询销售订单最后更新时间
   * @param search 查询条件
   * @return 销售订单最后更新时间
   */
  @Override
  public Date sellOrderLastUpdateTime(SellOrderSearchParamPo search) {
    return this.baseMapper.sellOrderLastUpdateTime(search);
  }

  /**
   * 多渠道订单
   */
  @Override
  public List<SellOrderItemVo> multiChannel(SellOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.multiChannel(search);
  }

  /**
   * 多渠道订单分页
   */
  @Override
  public Page<SellOrderItemVo> multiChannelPage(SellOrderSearchParamPo search) {
    Page<SellOrderItemVo> multiChannelPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return multiChannelPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return multiChannelPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    multiChannelPage =
      this.baseMapper.multiChannelPage(
          search.toPage(this.baseMapper.multiChannelCount(search)),
          search
        );
    if (
      search.getFillParts() == null || search.getFillParts().contains("details")
    ) {
      fillPartOfDetails(
        multiChannelPage.getRecords(),
        search.toChildSort("details")
      );
    }
    List<Long> recordIds = multiChannelPage
      .getRecords()
      .stream()
      .map(SellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return multiChannelPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return multiChannelPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    multiChannelPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return multiChannelPage;
  }

  /**
   * 查询多渠道订单最后更新时间
   * @param search 查询条件
   * @return 多渠道订单最后更新时间
   */
  @Override
  public Date multiChannelLastUpdateTime(SellOrderSearchParamPo search) {
    return this.baseMapper.multiChannelLastUpdateTime(search);
  }
}
